package com.zhongxi.guoyuan.view.user;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.code.CodeResult;
import com.zhongxi.guoyuan.entity.user.RegisterCheckResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.RegularTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    private EditText etPhone;
    private EditText etCode;
    private Button btSend;
    private Button btRegister;
    private Map<String, String> map = new HashMap<String, String>();
    private String phone;
    private String code;
    private String type;
    private CheckBox cb;
    private TextView tvAgreement;


    /*定义一个倒计时的内部类*/
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长，和计时的时间间隔
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            btSend.setClickable(false);
            btSend.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {//计时完毕时触发
            btSend.setText("发送验证码");
            btSend.setClickable(true);
        }

    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_register);
        initTitle();
        tvTitle.setText("注册会员");
        etPhone = (EditText) findViewById(R.id.etPhone);
        etCode = (EditText) findViewById(R.id.etCode);
        btSend = (Button) findViewById(R.id.btSend);
        btRegister = (Button) findViewById(R.id.btRegister);
        tvAgreement = (TextView) findViewById(R.id.tvAgreement);
        cb = (CheckBox) findViewById(R.id.cb);
    }

    @Override
    protected void initData() {
        super.initData();
    }

    private void getValue() {
        phone = etPhone.getText().toString().trim();
        code = etCode.getText().toString().trim();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        btSend.setOnClickListener(this);
        btRegister.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        tvAgreement.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btSend:
                sendCode();
                break;
            case R.id.btRegister:
                register();
                break;
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvAgreement:
                startAct(AgreementActivity.class);
                break;
        }
    }

    /**
     * 注册
     */
    private void register() {
        getValue();
        if (TextUtils.isEmpty(phone)) {
            showShortToast("手机号不能为空");
        } else if (TextUtils.isEmpty(code)) {
            showShortToast("验证码不能为空");
        } else if (!RegularTool.isPhoneNumberValid(phone)) {
            showShortToast("请输入正确的手机号");
        } else if (!cb.isChecked()) {
            showShortToast("请先同意注册条款");
        } else {
            type = "registerCheck";
            map.clear();
            map.put("mobilenum", phone);
            map.put("veriycode", code);
            map.put("msgid", MyApplication.getInstance().getMsgid());
            getServer(Url.REGISTER_CHECK, map, "", false, null, "post");
        }
    }

    /**
     * 发送验证码
     */
    @SuppressLint("NewApi")
    private void sendCode() {
        getValue();
        if (TextUtils.isEmpty(phone)) {
            showShortToast("手机号不能为空");
        } else if (!RegularTool.isPhoneNumberValid(phone)) {
            showShortToast("请输入正确的手机号");
        } else {
            type = "sendcode";
            TimeCount time = new TimeCount(60000, 1000);
            time.start();
            map.clear();
            map.put("mobilenum", phone);
            getServer(Url.SEND_CODE, map, "", false, null, "post");
        }
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        try {
            Gson gson = new Gson();
            if ("sendcode".equals(type)) {
                CodeResult result = gson.fromJson(response, CodeResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                MyApplication.getInstance().sharedPrefrences.edit().putString("msgid", result.getMsgid()).commit();
            } else if ("registerCheck".equals(type)) {
                RegisterCheckResult result = gson.fromJson(response, RegisterCheckResult.class);
                MyApplication.getInstance().sharedPrefrences.edit().putString("phone", phone).commit();
                MyApplication.getInstance().sharedPrefrences.edit().putString("useid", result.getId()).commit();
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                startAct(SetPasswordActivity.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void processOldUser(String response) {
        super.processOldUser(response);
        Gson gson = new Gson();
        RegisterCheckResult result = gson.fromJson(response, RegisterCheckResult.class);
        if (null != result.getSafeobj() && !"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        MyApplication.getInstance().sharedPrefrences.edit().putString("useid", result.getId()).commit();
        MyApplication.getInstance().setSpValue(result.getSafeobj());
        startAct(SetPasswordActivity.class);
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        try {
            JSONObject obj = new JSONObject(response);
            int errorcode = obj.getInt("code");
            if (errorcode == 1000) {
                showShortToast("参数错误");
            } else if (errorcode == 1100) {
                showShortToast("短信重复请求");
            } else if (errorcode == 1101) {
                showShortToast("短信服务失效");
            } else if (errorcode == 4001) {
                showShortToast("老用户,可直接登陆");
            } else if (errorcode == 4002) {
                showShortToast("老用户,须设置密码");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
